package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author Adam
 * @date 2025-07-23
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) throws Exception {
        //检验老人是否已入住
        //根据老人身份证号判断
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCardNo));
        if (elder != null) {
            throw new Exception("老人已入住");
        }
        //若为否,更新床位状态为已入住
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        bed.setBedStatus(1);
        //新增或更新老人
        elder = saveOrUpdateElder(dto, bed);
        //新增签约办理
        saveContract(elder, dto);
        //新增入住信息
        CheckIn checkIn = saveCheckIn(dto, elder);
        //新增入住配置
        saveCheckInConfig(dto, checkIn.getId());

    }

    /**
     * 新增入住配置信息
     *
     * @param dto
     * @param id
     */
    private void saveCheckInConfig(CheckInApplyDto dto, Long id) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);

        // 设置费用开始日期，根据业务需求设置合适的值
        // 这里假设费用开始日期与入住开始日期相同
        if (dto.getCheckInConfigDto().getStartDate() != null) {
            checkInConfig.setFeeStartDate(dto.getCheckInConfigDto().getStartDate());
        }

        checkInConfigMapper.insert(checkInConfig);
    }


    /**
     * 新增入住信息
     *
     * @param dto
     * @param elder
     */
    private CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());

        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0L);
        checkInMapper.insert(checkIn);
        return checkIn;


    }

    /**
     * 新增签约信息
     *
     * @param elder
     * @param dto
     */
    private void saveContract(Elder elder, CheckInApplyDto dto) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //添加合同号
        contract.setContractNumber("Ht" + CodeGenerator.generateContractNumber());
        //合同状态
        //签约时间判断
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(Long.valueOf(status));
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contractMapper.insert(contract);
    }

    /**
     * 新增或者更新老人
     *
     * @param dto
     * @param bed
     */
    private Elder saveOrUpdateElder(CheckInApplyDto dto, Bed bed) {
        // 准备老人数据
        Elder elder = new Elder();

        // 使用正确的 DTO 对象进行属性拷贝
        if (dto.getCheckInElderDto() != null) {
            BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        }

        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);

        // 查询老人信息，（身份证号、状态不为1）
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(elder);
        } else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 查询回显详情信息
     *
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //封装返回信息
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住信息
        //根据老人ID查询老人信息
        //查询老人的ID
        Long elderId = checkInMapper.selectOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getId, id)).getElderId();
        //查询老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectElderById(elderId);
        String birthday = elder.getBirthday();
        Integer age = null;

        if (birthday != null && !birthday.isEmpty()) {
            try {
                LocalDate birthDate = LocalDate.parse(birthday);
                LocalDate currentDate = LocalDate.now();
                age = Period.between(birthDate, currentDate).getYears();
            } catch (Exception e) {
                log.error("日期解析错误: ", e);
            }
        }
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //查询合同
        Contract contract = new Contract();
        contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elderId));
        checkInDetailVo.setContract(contract);
        //查询入住配置
        CheckIn checkIn = new CheckIn();
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkIn = checkInMapper.selectOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getElderId, elderId));
        BeanUtils.copyProperties(checkIn, checkInConfigVo);
        checkInConfigVo.setCheckInId(id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        checkInConfigVo.setNursingLevelId(checkInConfig.getNursingLevelId());
        checkInConfigVo.setFeeStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setFeeEndDate(checkInConfig.getFeeEndDate());
        checkInConfigVo.setDeposit(checkInConfig.getDeposit());
        checkInConfigVo.setNursingFee(checkInConfig.getNursingFee());
        checkInConfigVo.setBedFee(checkInConfig.getBedFee());
        checkInConfigVo.setInsurancePayment(checkInConfig.getInsurancePayment());
        checkInConfigVo.setGovernmentSubsidy(checkInConfig.getGovernmentSubsidy());
        checkInConfigVo.setOtherFees(checkInConfig.getOtherFees());

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //转换家属列表
        List<ElderFamilyVo> familyVos = JSON.parseArray(checkInMapper.selectOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getElderId, elderId)).getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(familyVos);
        //整合数据返回
        return checkInDetailVo;
    }
}
